//1.引入 express  mvc框架
//如果是多次引入,会去读之前的缓存
const express = require('express'); // http
const moment = require('moment');
const db = require("../core/DBHelper");
const file = require("../core/FileHelper")
    //2. 创建保安 聘请保安大爷
const apiRoutes = express.Router();
//3.给保安排管理任务
// post 登录
apiRoutes.post("/login", async(request, response, next) => {
        const userObj = request.body; //得到前端传过来的数据

        let sqlLogin = "SELECT `u_id`,`u_name`,`u_nickname`,`u_phone`,`u_createtime`"
        sqlLogin += " FROM `userinfo` WHERE u_name=? AND u_pwd=? AND u_status=1 ;";
        let params = [
            userObj.name,
            userObj.pwd
        ]
        try {
            let res = await db.exec(sqlLogin, params);
            const result = { msg: "登录成功", code: 200, status: 0 }
            if (res && res.length >= 1) {
                result["msg"] = "登录成功";
                result['status'] = 1;
                //   moment需要安装  cnpm i moment --save-dev
                res[0].u_create = moment(res[0].u_create).format("YYYY-MM-DD hh:mm:ss")
                result["data"] = res[0]
            }
            setTimeout(() => response.json(result), 1000);
        } catch (error) {
            response.json({
                msg: "登录失败",
                code: -200,
                error
            })
        }
    })
    //post 注册
apiRoutes.post("/reg", async(request, response, next) => {
        //1.接收到前端发送过来的参数
        let userObj = request.body;
        //2.准备sql语句和参数
        let regSql = "INSERT INTO `userinfo` (`u_name`,`u_pwd`,`u_nickname`,`u_phone`,`u_createtime`) ";
        regSql += "VALUES(?,?,?,?,?);";

        let params = [
            userObj.name, //用户名
            userObj.pwd, //密码
            userObj.nickname, //昵称
            userObj.phone, //手机号
            moment(Date.now()).format("YYYY-MM-DD hh:mm:ss")
        ]

        try {
            let res = await db.exec(regSql, params);
            let isReg = (res && res.affectedRows >= 1); //true or false
            let result = {
                msg: isReg ? '注册成功' : '注册失败',
                code: 200
            }
            response.json(result)
        } catch (error) {
            let result = {
                msg: '注册失败',
                code: -200,
                error
            }
            response.json(result)
        }

    })
    //get 检查用户名

apiRoutes.get("/checkName", async(request, response, next) => {
    let { name } = request.query;

    let sql = "SELECT *FROM userinfo WHERE u_status =1 AND u_name=? ;";
    let result = await db.exec(sql, [name]);
    let res = !(result && result.length >= 1);
    //用户名存在,返回false,true可以注册
    response.send(res);
})



//获取产品列表
apiRoutes.get("/getList", async(request, response, next) => {
    // apiRoutes里的代码都会在 app.js里运行
    let res = await file.getFile("../data/list.json");
    response.send(res);
})

apiRoutes.get("/getByPid", async(request, response, next) => {
    // apiRoutes里的代码都会在 app.js里运行
    let { pId } = request.query;
    let res = await file.getFile("../data/list.json");
    let list = JSON.parse(res || '[]')
    var goodsObj = list.find((el, index) => {
        return el.pid == pId
    })

    response.json(goodsObj);

})

//加入购物车
apiRoutes.post("/addCart", async(request, response, next) => {
    let { u_id, pprice, pname, pid, num, index_img } = request.body;

    let sqlQuery = "SELECT * FROM `carts`  WHERE `c_status`=1 AND `p_id`=? AND `u_id`=?";
    let paramsQuery = [pid, u_id]


    try {

        let queryResult = await db.exec(sqlQuery, paramsQuery)
        let isAdd = (queryResult && queryResult.length >= 1); //已购买

        if (isAdd) { //已购买,修改数量和总金额
            let sqlUpdate = "UPDATE carts SET`p_number`=p_number+? ,`p_total`=p_number*`p_price` WHERE `c_status`=1 AND `p_id`=? AND `u_id`=?";
            let paramsUpdate = [num, pid, u_id];
            let updateResult = await db.exec(sqlUpdate, paramsUpdate);
            let updateIsSuccess = (updateResult && updateResult.affectedRows >= 1)
            if (updateIsSuccess) {
                response.json({ msg: "加入购物车成功", flag: "update", code: 200 })
            } else {
                response.json({ msg: "加入购物车失败", flag: "update", code: 200 })
            }
        } else { //从来没购买过,插入1条新的数据

            let sqlInert = "INSERT INTO `carts` (`p_id`,`p_name`,`p_price`,`p_number`,`p_total`,`p_create`,`p_img`,`u_id`)VALUE(?,?,?,?,?,?,?,?)";
            let paramsInert = [
                pid,
                pname,
                pprice,
                num,
                pprice * num,
                moment(Date.now()).format("YYYY-MM-DD hh:mm:ss"),
                index_img,
                u_id
            ]

            let inserResult = await db.exec(sqlInert, paramsInert);

            let inserIsSuccess = (inserResult && inserResult.affectedRows >= 1)

            response.json({ msg: inserIsSuccess ? "加入购物车成功" : "加入购物车失败", flag: "insert", code: 200 })

        }
    } catch (error) {
        response.json({ msg: inserIsSuccess ? "加入购物车失败" : "加入购物车失败", error, code: -200 })
    }


})


//购物车列表
apiRoutes.get("/cartlist", async(request, response) => {
    let { userId } = request.query; // {userId:1}

    let queryCart = "SELECT *FROM `carts` WHERE c_status=1 AND u_id=?;";

    let params = [userId]
    let result = await db.exec(queryCart, params);

    response.json({
        msg: "查询成功",
        code: 200,
        data: result
    })
})


apiRoutes.post("/update", async(request, response) => {
    let { c_id, num } = request.body;

    let sql = "UPDATE carts SET `p_number`=?,`p_total`=p_number*`p_price` WHERE `c_id`=? AND`c_status`=1;";

    let params = [num, c_id]

    try {
        let result = await db.exec(sql, params);
        let isUpdate = (result && result.affectedRows >= 1);

        response.json({
            msg: isUpdate ? "修改成功" : "修改失败",
            code: 200,
            status: Number(isUpdate)
        })
    } catch (error) {
        response.json({
            msg: "修改失败",
            code: -200,
            status: 0,
            error
        })
    }

})

//软删除
apiRoutes.post("/delete", async(request, response) => {
    let { c_id } = request.body;

    let sql = "UPDATE carts SET `c_status`=0 WHERE `c_id`=?;";
    let params = [
        c_id
    ]
    let result = await db.exec(sql, params);

    let isDelete = (result && result.affectedRows >= 1);
    response.json({
        msg: isDelete ? "删除成功" : "删除失败",
        code: 200,
        status: Number(isDelete)
    })

})






//4.保留保安
module.exports = { apiRoutes };